package org.niux.aims.dao.impl;

import java.util.List;
import java.util.logging.Level;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.niux.aims.dao.IAuthDAO;
import org.niux.aims.models.Auth;
import org.niux.aims.models.EntityManagerHelper;
import org.springframework.stereotype.Repository;

/**
 * 
 * Copyright (c) 2009,niux<br>
 * All rights reserved.<br>
 * 
 * 文件名称：AuthDAO.java<br>
 * 摘    要：权限数据操作类<br>
 * <br>
 * 当前版本：<br>
 * 作    者：铭显 Email: <a href="mailto:liangmingxian@gmail.com">liangmingxian@gmail.com</a><br>
 * 完成日期：@since 2013-9-5<br>
 * <br>
 * 取代版本：<br>
 * 原作者  ：<br>
 * 完成日期：@since Oct 22, 2009<br>
 */
@Repository(value="authDao")
public class AuthDAO implements IAuthDAO {
	// property constants

	private EntityManager getEntityManager() {
		return EntityManagerHelper.getEntityManager();
	}

	/**
	 * 
	 * 方法概述：保存权限数据
	 * 描述：保存权限数据
	 * @param entity
	 * 返回类型：
	 * 修改人：梁铭显
	 * 修改时间：2013-9-5
	 */
	public void save(Auth entity) {
		try {
			getEntityManager().getTransaction().begin();
			getEntityManager().persist(entity);
			getEntityManager().getTransaction().commit();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	/**
	 * Delete a persistent Auth entity. This operation must be performed within
	 * the a database transaction context for the entity's data to be
	 * permanently deleted from the persistence store, i.e., database. This
	 * method uses the {@link javax.persistence.EntityManager#remove(Object)
	 * EntityManager#delete} operation.
	 * 
	 * <pre>
	 * EntityManagerHelper.beginTransaction();
	 * AuthDAO.delete(entity);
	 * EntityManagerHelper.commit();
	 * entity = null;
	 * </pre>
	 * 
	 * @param entity
	 *            Auth entity to delete
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void delete(Auth entity) {
		EntityManagerHelper.log("deleting Auth instance", Level.INFO, null);
		try {
			entity = getEntityManager()
					.getReference(Auth.class, entity.getId());
			getEntityManager().remove(entity);
			EntityManagerHelper.log("delete successful", Level.INFO, null);
		} catch (RuntimeException re) {
			EntityManagerHelper.log("delete failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * Persist a previously saved Auth entity and return it or a copy of it to
	 * the sender. A copy of the Auth entity parameter is returned when the JPA
	 * persistence mechanism has not previously been tracking the updated
	 * entity. This operation must be performed within the a database
	 * transaction context for the entity's data to be permanently saved to the
	 * persistence store, i.e., database. This method uses the
	 * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge}
	 * operation.
	 * 
	 * <pre>
	 * EntityManagerHelper.beginTransaction();
	 * entity = AuthDAO.update(entity);
	 * EntityManagerHelper.commit();
	 * </pre>
	 * 
	 * @param entity
	 *            Auth entity to update
	 * @return Auth the persisted Auth entity instance, may not be the same
	 * @throws RuntimeException
	 *             if the operation fails
	 */
	public Auth update(Auth entity) {
		EntityManagerHelper.log("updating Auth instance", Level.INFO, null);
		try {
			Auth result = getEntityManager().merge(entity);
			EntityManagerHelper.log("update successful", Level.INFO, null);
			return result;
		} catch (RuntimeException re) {
			EntityManagerHelper.log("update failed", Level.SEVERE, re);
			throw re;
		}
	}

	public Auth findById(Integer id) {
		EntityManagerHelper.log("finding Auth instance with id: " + id,
				Level.INFO, null);
		try {
			Auth instance = getEntityManager().find(Auth.class, id);
			return instance;
		} catch (RuntimeException re) {
			EntityManagerHelper.log("find failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * 
	 * 方法概述：根据字段获取权限分配数据
	 * 描述：根据字段获取权限分配数据
	 * @param propertyName
	 * @param value
	 * @param rowStartIdxAndCount
	 * @return
	 * 返回类型：
	 * 修改人：梁铭显
	 * 修改时间：2013-9-5
	 */
	@SuppressWarnings("unchecked")
	public List<Auth> findByProperty(String propertyName, final Object value,
			final int... rowStartIdxAndCount) {
		try {
			final String queryString = "select model from Auth model where model."
					+ propertyName + "= :propertyValue";
			Query query = getEntityManager().createQuery(queryString);
			query.setParameter("propertyValue", value);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	/**
	 * Find all Auth entities.
	 * 
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            count of results to return.
	 * @return List<Auth> all Auth entities
	 */
	@SuppressWarnings("unchecked")
	public List<Auth> findAll(final int... rowStartIdxAndCount) {
		EntityManagerHelper.log("finding all Auth instances", Level.INFO, null);
		try {
			final String queryString = "select model from Auth model";
			Query query = getEntityManager().createQuery(queryString);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			EntityManagerHelper.log("find all failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * 
	 * 方法概述：根据账户获取权限分配数据
	 * 描述：根据账户获取权限分配数据
	 * @param accountid
	 * @return
	 * 返回类型：List<Auth>
	 * 修改人：梁铭显
	 * 修改时间：2013-9-5
	 */
	@SuppressWarnings("unchecked")
	public List<Auth> findByAccount(int accountid){
		StringBuffer hql = new StringBuffer();
		
		hql.append("SELECT auth ");
		hql.append("FROM Auth auth ");
		hql.append("LEFT JOIN FETCH auth.account account ");
		hql.append("WHERE 1 = 1 ");
		hql.append("AND account.id = :accountid ");
		
		Query query = getEntityManager().createQuery(hql.toString());
		
		query.setParameter("accountid", accountid);
		
		return query.getResultList();
	}
}